package com.atguigu.security.security;

import com.atguigu.servicebase.utils.R;
import com.atguigu.servicebase.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义退出处理器, LogoutHandler是由SpringSecurity提供的接口
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager,RedisTemplate redisTemplate){
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }


    //退出处理器主要完成两件事,第一件事是将token从header中进行删除,第二件事是从redis中删除
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从header中获取token
        String token = request.getHeader("token");
        //如果token不为空,则移除token,并从redis中进行删除
        if(token != null){
            //移除token
            this.tokenManager.removeToken(token);
            //从token中获取用户名
            String userName = this.tokenManager.getUserInfoFromToken(token);
            //从redis中删除(key为userName, value放置的是权限列表)
            this.redisTemplate.delete(userName);
        }
        //完成后返回一些信息
        ResponseUtil.out(response, R.ok());
    }

}
